<template>
  <div class="app-manager-page">
    <div class="page-header">
      <h1>应用管理</h1>
      <p>管理系统中的所有应用，包括查看、编辑、删除和设置精选状态</p>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-card size="small">
            <a-statistic title="应用总数" :value="appList.totalRow" />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card size="small">
            <a-statistic title="当前页数量" :value="appList.records?.length || 0" />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card size="small">
            <a-statistic title="精选应用" :value="featuredCount" />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card size="small">
            <a-statistic title="总页数" :value="appList.totalPage" />
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-input
            v-model:value="searchForm.appName"
            placeholder="应用名称"
            allow-clear
            @change="handleSearch"
          />
        </a-col>
        <a-col :span="4">
          <a-select
            v-model:value="searchForm.codeGenType"
            placeholder="代码类型"
            allow-clear
            @change="handleSearch"
          >
            <a-select-option value="react">React</a-select-option>
            <a-select-option value="vue">Vue</a-select-option>
            <a-select-option value="html">HTML</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="4">
          <a-select
            v-model:value="searchForm.isFeatured"
            placeholder="精选状态"
            allow-clear
            @change="handleSearch"
          >
            <a-select-option :value="true">已精选</a-select-option>
            <a-select-option :value="false">未精选</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="4">
          <a-button type="primary" @click="handleSearch">
            <SearchOutlined />
            搜索
          </a-button>
          <a-button style="margin-left: 8px" @click="handleReset">
            <ReloadOutlined />
            重置
          </a-button>
        </a-col>
      </a-row>
    </div>

    <!-- 应用列表 -->
    <div class="table-section">
      <a-table
        :columns="columns"
        :data-source="appList.records"
        :loading="loading"
        :pagination="false"
        row-key="id"
        size="middle"
      >
        <!-- 应用名称 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'appName'">
            <div class="app-info">
              <div class="app-cover">
                <img v-if="record.cover" :src="record.cover" :alt="record.appName" />
                <div v-else class="cover-placeholder">
                  <AppstoreOutlined />
                </div>
              </div>
              <div class="app-details">
                <div class="app-name">{{ record.appName }}</div>
                <div class="app-meta">
                  <span>ID: {{ record.id }}</span>
                  <span v-if="record.user">用户: {{ record.user.userName }}</span>
                </div>
              </div>
            </div>
          </template>

          <!-- 代码类型 -->
          <template v-else-if="column.key === 'codeGenType'">
            <a-tag :color="getCodeTypeColor(record.codeGenType)">
              {{ record.codeGenType }}
            </a-tag>
          </template>

          <!-- 优先级 -->
          <template v-else-if="column.key === 'priority'">
            <a-tag :color="record.priority === 100 ? 'green' : 'default'">
              {{ record.priority }}
            </a-tag>
          </template>

          <!-- 创建时间 -->
          <template v-else-if="column.key === 'createTime'">
            {{ formatTime(record.createTime) }}
          </template>

          <!-- 操作 -->
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleViewApp(record)">
                <EyeOutlined />
                查看
              </a-button>
              <a-button type="link" size="small" @click="handleEditApp(record)">
                <EditOutlined />
                编辑
              </a-button>
              <a-button
                type="link"
                size="small"
                :danger="record.priority === 100"
                @click="handleToggleFeatured(record)"
              >
                <StarOutlined v-if="record.priority === 100" />
                <StarFilled v-else />
                {{ record.priority === 100 ? '取消精选' : '设为精选' }}
              </a-button>
              <a-popconfirm title="确定要删除这个应用吗？" @confirm="handleDeleteApp(record)">
                <a-button type="link" size="small" danger>
                  <DeleteOutlined />
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <a-pagination
          v-model:current="searchForm.pageNum"
          v-model:pageSize="searchForm.pageSize"
          :total="appList.totalRow"
          :show-size-changer="true"
          :show-quick-jumper="true"
          :show-total="
            (total: any, range: any[]) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
          "
          @change="handlePageChange"
          @showSizeChange="handlePageChange"
        />
      </div>
    </div>

    <!-- 编辑应用弹窗 -->
    <a-modal
      v-model:open="editModalVisible"
      title="编辑应用信息"
      @ok="handleEditSubmit"
      @cancel="handleEditCancel"
      :confirm-loading="editLoading"
    >
      <a-form ref="editFormRef" :model="editForm" :rules="editRules" layout="vertical">
        <a-form-item label="应用名称" name="appName">
          <a-input v-model:value="editForm.appName" placeholder="请输入应用名称" />
        </a-form-item>
        <a-form-item label="应用封面" name="cover">
          <a-input v-model:value="editForm.cover" placeholder="请输入封面图片URL" />
        </a-form-item>
        <a-form-item label="优先级" name="priority">
          <a-input-number
            v-model:value="editForm.priority"
            :min="0"
            :max="999"
            placeholder="请输入优先级"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  SearchOutlined,
  ReloadOutlined,
  AppstoreOutlined,
  EyeOutlined,
  EditOutlined,
  StarOutlined,
  StarFilled,
  DeleteOutlined
} from '@ant-design/icons-vue'
import { listAppByPage, updateApp, deleteApp, setAppFeature } from '@/api/guanliyuanjiekou'

const router = useRouter()

// 表格列定义
const columns = [
  {
    title: '应用信息',
    key: 'appName',
    width: 300
  },
  {
    title: '代码类型',
    key: 'codeGenType',
    width: 120
  },
  {
    title: '优先级',
    key: 'priority',
    width: 100
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180
  },
  {
    title: '操作',
    key: 'action',
    width: 300
  }
]

// 搜索表单
const searchForm = reactive({
  pageNum: 1,
  pageSize: 20,
  appName: '',
  codeGenType: '',
  userId: undefined as string | undefined,
  isFeatured: undefined as boolean | undefined
})

// 应用列表数据
const appList = reactive<API.PageAppVO>({
  records: [],
  totalRow: 0,
  pageNumber: 1,
  pageSize: 20,
  totalPage: 0,
  optimizeCountQuery: true
})

// 加载状态
const loading = ref(false)

// 精选应用数量
const featuredCount = computed(() => {
  return appList.records?.filter(app => app.priority === 100).length || 0
})

// 编辑弹窗
const editModalVisible = ref(false)
const editLoading = ref(false)
const editFormRef = ref()
const editForm = reactive({
  id: '',
  appName: '',
  cover: '',
  priority: 0
})

// 编辑表单验证规则
const editRules = {
  appName: [{ required: true, message: '请输入应用名称', trigger: 'blur' }],
  priority: [{ required: true, message: '请输入优先级', trigger: 'blur' }]
}

// 加载应用列表
const loadAppList = async () => {
  loading.value = true
  try {
    const response = await listAppByPage(searchForm)
    if (response.data.code === 200 && response.data.data) {
      Object.assign(appList, response.data.data)
    }
  } catch (error) {
    message.error('加载应用列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  searchForm.pageNum = 1
  loadAppList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    pageNum: 1,
    pageSize: 20,
    appName: '',
    codeGenType: '',
    userId: undefined,
    isFeatured: undefined
  })
  loadAppList()
}

// 分页变化
const handlePageChange = (page: number, pageSize: number) => {
  searchForm.pageNum = page
  searchForm.pageSize = pageSize
  loadAppList()
}

// 查看应用
const handleViewApp = (record: API.AppVO) => {
  if (record.id) {
    router.push(`/app/detail/${record.id}`)
  }
}

// 编辑应用
const handleEditApp = (record: API.AppVO) => {
  Object.assign(editForm, {
    id: record.id,
    appName: record.appName,
    cover: record.cover,
    priority: record.priority
  })
  editModalVisible.value = true
}

// 提交编辑
const handleEditSubmit = async () => {
  try {
    await editFormRef.value?.validate()
    editLoading.value = true

    const response = await updateApp(editForm)
    if (response.data.code === 200) {
      message.success('更新成功')
      editModalVisible.value = false
      loadAppList()
    } else {
      message.error(response.data.message || '更新失败')
    }
  } catch (error) {
    console.error(error)
  } finally {
    editLoading.value = false
  }
}

// 取消编辑
const handleEditCancel = () => {
  editModalVisible.value = false
  editFormRef.value?.resetFields()
}

// 切换精选状态
const handleToggleFeatured = async (record: API.AppVO) => {
  if (!record.id) return

  try {
    const isFeatured = record.priority === 100

    const response = await setAppFeature({
      id: record.id,
      isFeatured: !isFeatured
    })

    if (response.data.code === 200) {
      message.success(isFeatured ? '已取消精选' : '已设为精选')
      loadAppList()
    } else {
      message.error(response.data.message || '操作失败')
    }
  } catch (error) {
    message.error('操作失败')
    console.error(error)
  }
}

// 删除应用
const handleDeleteApp = async (record: API.AppVO) => {
  if (!record.id) return

  try {
    const response = await deleteApp({ id: record.id })
    if (response.data.code === 200) {
      message.success('删除成功')
      loadAppList()
    } else {
      message.error(response.data.message || '删除失败')
    }
  } catch (error) {
    message.error('删除失败')
    console.error(error)
  }
}

// 获取代码类型颜色
const getCodeTypeColor = (type?: string) => {
  switch (type) {
    case 'react':
      return 'blue'
    case 'vue':
      return 'green'
    case 'html':
      return 'orange'
    default:
      return 'default'
  }
}

// 格式化时间
const formatTime = (timeStr?: string) => {
  if (!timeStr) return ''
  return new Date(timeStr).toLocaleString('zh-CN')
}

// 页面加载时获取数据
onMounted(() => {
  loadAppList()
})
</script>

<style scoped>
.app-manager-page {
  padding: 24px;
  background: white;
  border-radius: 8px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1a1a1a;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.stats-section {
  margin-bottom: 24px;
}

.stats-section .ant-card {
  text-align: center;
}

.search-section {
  margin-bottom: 24px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.table-section {
  margin-bottom: 24px;
}

.app-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.app-cover {
  width: 48px;
  height: 48px;
  border-radius: 6px;
  overflow: hidden;
  flex-shrink: 0;
}

.app-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cover-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f0f0f0;
  color: #999;
  font-size: 20px;
}

.app-details {
  flex: 1;
  min-width: 0;
}

.app-name {
  font-weight: 500;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.app-meta {
  font-size: 12px;
  color: #999;
  display: flex;
  gap: 12px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-manager-page {
    padding: 16px;
  }

  .search-section {
    padding: 12px;
  }

  .app-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .app-cover {
    width: 40px;
    height: 40px;
  }
}
</style>
